export default {
  name: 'addGoods',
  data () {
    return {
      id: this.$route.params.id,
      active: 0,
      tabPosition: 'left',
      goodsInfo: {},
      dazhe: false,
      goodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'change' },
          { min: 3, max: 10, message: '名称在 3 到 10 字符间', trigger: 'change' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'change' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'change' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'change' }
        ]
      },
      goods_cat: [],
      cateList: [],
      categoriesList: [],
      inputValue: '',
      firstFinish: false,
      secondFinish: false
    }
  },
  async created () {
    this.getCateList()
    if (this.id - 0) {
      this.getEditGoodsHandler(this.id)
    }
  },
  methods: {
    async getCateList () {
      const { data } = await this.$get('categories', { type: 3 })
      this.cateList = data
      // console.log(this.id)
    },
    selectHandler () {
      if (this.dazhe) {
        this.dazhe = false
      } else this.dazhe = true
    },
    next (tab) {
      this.active = tab.index - 0
      if (tab.index - 0 !== 0) {
        this.$refs.goodsRule.validate(res => {
          if (!res || this.goods_cat.length !== 3) {
            this.$message({
              type: 'error',
              message: '请完整填写商品信息'
            })
          }
        })
      } else this.firstFinish = true
    },
    async getCategoriesList () {
      const { data } = await this.$get(`categories/${this.goods_cat[2]}/attributes`, { params: { sel: 'many' } })
      this.categoriesList = data
      this.categoriesList.forEach(item => {
        item.attr_vals = item.attr_vals.split(',')
        this.secondFinish = true
      })
    },
    async getEditGoodsHandler (id) {
      const { data } = await this.$get(`goods/${id}`)
      this.goodsInfo = data
      console.log(data)
      this.goods_cat = [data.cat_one_id, data.cat_two_id, data.cat_three_id]
    },
    async submitHandler () {
      this.$refs.goodsRule.validate(async res => {
        if (res) {
          if (this.id - 0 === 0) {
            if (!this.secondFinish) {
              this.$message({
                type: 'error',
                message: '请选择商品参数'
              })
              return
            }
          }
          this.goodsInfo.goods_cat = this.goods_cat
          const { meta } = await this.$post('goods', this.goodsInfo)
          console.log(meta)
        }
        if (!res || this.goods_cat.length !== 3) {
          this.$message({
            type: 'error',
            message: '请完整填写商品信息'
          })
        }
      })
    }
  },
  watch: {
    goods_cat () {
      this.getCategoriesList()
    }
  },
  filters: {
    fil (val) {
      return !(val - 0) ? '添加商品' : '编辑商品'
    }
  }
}
